<template>
  <el-dialog title="批量导入" class="import-dialog" :visible="visible" @close="close('close-icon')">
    <el-steps finish-status="success" :active="active" align-center>
      <el-step title="上传文件" />
      <el-step title="执行导入" />
      <el-step title="导入完成" />
    </el-steps>
    <section v-show="active===0">
      <div class="im-block">
        <p class="icon"><i class="el-icon-document" /></p>
        <div class="desc">
          <p class="title">填写导入商品的信息</p>
          <p class="title-desc">请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除</p>
          <div class="control-box">
            <elink-loading class="control" :name="'下载模板'" :text-loading="textLoading" @clickDown="downloadTemplate" />
            <upload-files ref="uploadFiles" class="control" @onSuccess="setFile" />
          </div>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button v-debounce="judgeImport" type="primary">下一步</el-button>
      </div>
    </section>
    <section v-show="active===1">
      <div class="im-block">
        <p class="icon"><i class="el-icon-document-checked" /></p>
        <div class="desc">
          <p class="title">本次导入商品条数</p>
          <div class="control-box">
            <el-link type="primary" :underline="false" class="control">{{ judgmentResult.correctNum }}个</el-link>
          </div>
        </div>
      </div>
      <div class="im-block">
        <p class="icon"><i class="el-icon-document-delete" /></p>
        <div class="desc">
          <p class="title">本次不可导入商品条数</p>
          <div class="control-box">
            <el-link type="primary" :underline="false" class="control">{{ judgmentResult.errorNum }}个</el-link>
          </div>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button v-debounce="()=>{isImport(1)}" type="primary" :icon="isImportBtn===1?`el-icon-loading`:``" :disabled="judgeImportComplete">确认导入</el-button>
        <el-button v-debounce="()=>{isImport(0)}" :icon="isImportBtn===0?`el-icon-loading`:``" :disabled="judgeImportComplete">返回重新上传</el-button>
      </div>
      <section v-if="judgmentResult.dataList&&judgmentResult.dataList.length" class="table-area">
        <span class="desc">不可导入商品明细</span>
        <elink-loading class="control" :name="'下载错误数据'" :text-loading="textLoading" @clickDown="downloadErrorData" />
        <table-pagination class="error-table" :layout="'total, prev, pager, next'" :columns="columns" :data="judgmentResult.dataList" :current-page="currentPage" :total="total" border @handlePaginationChange="handlePaginationChange" />
      </section>
    </section>
    <section v-show="active===2" class="complete">
      <i class="el-icon-success" />
      <p>批量导入完成</p>
      <span class="title-desc">成功导入商品数量:{{ totalCorrectNum }}条</span>
      <div class="dialog-footer">
        <el-button type="primary" @click="close">完 成</el-button>
      </div>
    </section>
    <section v-show="active===1&&progressSection" class="progress">
      <div class="progress-box">
        <el-progress v-show="progressShow" type="circle" :percentage="uploadPercentage" :stroke-width="16" :format="uploadProgressFormat" :width="200" />
        <el-progress v-show="progressAxios" type="circle" :percentage="percentage" :stroke-width="16" :format="format" :width="200" />
      </div>
    </section>
  </el-dialog>
</template>
<script>

import UploadFiles from '@/components/common/UploadFiles';
import TablePagination from '@/components/common/TablePagination';
import ElinkLoading from './elinkLoading.vue';
import { whiteBlackList, confirmImport, downloadTemplate, exportErrorData, getErrorPage } from '@/api/replacementApi';
import { exportFile } from '@/utils/tools';
import config from './config';
export default {
  name: 'ImportFile',
  components: {
    UploadFiles,
    TablePagination,
    ElinkLoading
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    importType: {
      type: String,
      default: 'whitelist'
    },
    date: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      active: 0,
      columns: config.errorColumns,
      judgmentResult: {
        correctNum: '-',
        errorNum: '-',
        dataList: []
      },
      percentage: 0,
      uploadPercentage: 0,
      progressShow: false,
      progressAxios: false,
      progressSection: false,
      file: '',
      isImportBtn: null,
      judgeImportComplete: false,
      totalCorrectNum: '-',
      currentPage: 1,
      total: 0,
      textLoading: null
    };
  },
  watch: {
    progressAxios(val) {
      if (val) {
        const timer = setInterval(() => {
          if (this.percentage < 99) {
            this.percentage += 1;
          } else {
            clearInterval(timer);
          }
        }, 100);
      }
    }
  },
  methods: {
    setFile(fileList) {
      this.file = fileList[0];
    },
    uploadProgressFormat(percentage) {
      if (percentage === 100) {
        setTimeout(() => {
          this.progressShow = false;
          this.uploadPercentage = 0;
          this.progressAxios = true;
        }, 300);
      }
      return `${percentage}%`;
    },
    format(percentage) {
      return `上传完毕,解析中${percentage}%`;
    },
    handlePaginationChange({ current, size }) {
      getErrorPage({ current: current, size: size }).then((data) => {
        this.currentPage = current;
        this.judgmentResult.dataList = data.data;
      });
    },
    // 执行导入逻辑判断
    judgeImport() {
      if (!this.file) {
        this.$message.warning('请导入文件！');
        return;
      }
      this.active = 1;
      this.uploadPercentage = 0;
      this.percentage = 0;
      this.progressAxios = false;
      this.progressSection = true;
      this.progressShow = true;
      const formData = new FormData();
      formData.append('file', this.file.raw);
      formData.append('date', this.moment(this.date).format('YYYY/MM/DD'));
      whiteBlackList(this.importType, formData, this.onUploadProgress).then(({ data, resultCode }) => {
        this.judgmentResult = data;
        this.total = this.judgmentResult.errorNum;
        this.percentage = 100;
        setTimeout(() => {
          this.progressSection = false;
          this.progressAxios = false;
        }, 1000);
      }).catch(() => {
        this.percentage = 100;
        setTimeout(() => {
          this.progressSection = false;
          this.progressShow = false;
          this.progressAxios = false;
        }, 1000);
      });
    },
    // 确认导入或返回重新上传
    isImport(proceed) {
      this.judgeImportComplete = true;
      this.isImportBtn = proceed;
      confirmImport({ date: this.date, proceed: proceed }).then(res => {
        this.judgeImportComplete = false;
        this.isImportBtn = null;
        if (res.resultCode === '0000') {
          if (!proceed) {
            this.resetData();
          } else {
            this.totalCorrectNum = res.data;
            this.active = 2;
            this.$emit('complete');
          }
        } else {
          this.resetData();
        }
      }).catch(() => {
        this.isImportBtn = null;
        this.judgeImportComplete = false;
        this.resetData();
      });
    },
    onUploadProgress(progressEvent) {
      // progressEvent.loaded:已上传文件大小
      // progressEvent.total:被上传文件的总大小
      this.uploadPercentage = (progressEvent.loaded / progressEvent.total * 100);
    },
    // 完成关闭弹窗
    close(type) {
      if (type === 'close-icon' && this.judgeImportComplete) {
        const info = this.isImportBtn ? '文件导入中，请稍后' : '撤销操作中，请稍后';
        this.$message.info(info);
        return;
      }
      this.$emit('close');
      this.resetData();
    },
    // 重置数据
    resetData() {
      this.$nextTick(() => {
        this.active = 0;
        this.judgmentResult = {
          correctNum: '-',
          errorNum: '-',
          dataList: []
        };
        this.$refs.uploadFiles.delFile();
        this.totalCorrectNum = '-';
      });
    },
    // 下载模板
    downloadTemplate() {
      this.textLoading = '下载模板';
      downloadTemplate().then(res => {
        exportFile(res, '导入模板.xlsx');
        this.textLoading = null;
      });
    },
    // 下载错误数据
    downloadErrorData() {
      this.textLoading = '下载错误数据';
      exportErrorData().then(res => {
        if (res.type === 'application/json') {
          // 说明是普通对象数据，后台转换失败
          const reader = new FileReader();
          reader.readAsText(res, 'utf-8');
          reader.onload = () => {
            const jsonData = JSON.parse(reader.result);
            this.$message.error(jsonData.resultMessage);
          };
        } else {
          // 说明是正常的文件流
          exportFile(res, '错误数据.xlsx');
        }
        this.textLoading = null;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.import-dialog{
  .title-desc{
    font-size: 12px;
    color: #999;
  }
  .progress{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: self-start;
    .progress-box{
      height: 542px;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .im-block{
    width: 100%;
    height: 100px;
    display: flex;
    border: 1px solid #eee;
    align-items: center;
    margin: 20px 0;
    .icon{
      width: 80px;
      background-color: #eee;
      margin: 0;
      height: 100px;
      margin-right: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
    }
    .title,.title-desc,.control{
      margin-bottom: 4px;
    }
    .control-box{
      display: flex;
      align-items: center;
    }
    .control{
      font-size: 12px;
      padding-right: 10px;
    }
  }
  .dialog-footer{
    text-align: center;
  }
  .table-area{
    margin: 20px 0;
    .desc{
      font-size: 12px;
      padding-right: 10px;
    }
    .error-table{
    margin-top: 10px;
    }
  }
  .complete{
    margin-top: 10px;
    text-align: center;
    .el-icon-success{
      font-size: 100px;
      color: #67c23a;
    }
    .dialog-footer{
      margin-top: 20px;
    }
    p{
      margin: 0;
      font-size: 20px;
    }
  }
}
::v-deep {
  .el-steps--horizontal{
    position: relative;
    left: -18%;
    width: 136%;
  }
  .el-step__title.is-success {
    font-weight: 700;
    color: #303133;
  }
  .el-step__head.is-success {
    color: #409eff;
    border-color: #409eff;
  }
  .el-step__title{
    font-size: 14px;
  }
  .el-upload-list__item:first-child {
    margin-top: 0;
  }
  .el-step__head.is-process {
    color: #409eff;
    border-color: #409eff;
  }
  .el-progress--circle .el-progress__text, .el-progress--dashboard .el-progress__text{
    font-size: 16px!important;
  }
}
</style>
